package edu.qd.learn.day07;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 双向连表
 *
 * @author 布衣
 */
public class DoubleLink<E> {

    private Node<E> head;
    private Node<E> tail;
    private Node<E> middle;

    // 默认10  0
    List<String> list = new LinkedList<>();
//    list.add(10); >> 10 >>1
//   10W --- 8w  2W

    private int size;

    private class Node<E>{
        // 前一个节点
        Node<E> prev;
        //数据
        E data;
        // 后一个节点
        Node<E> next;

        public Node(E data) {
            this.data = data;
        }

        public Node(Node<E> prev,E data){
            this.prev = prev;
            this.data = data;
        }

        public Node(Node<E> prev,E data,Node<E> next){
            this.prev = prev;
            this.data = data;
            this.next = next;
        }
    }

    public void add(E val){
        size++;
        if(head == null){
            head = new Node<>(val);
            tail = head;
            middle = head;
            return ;
        }
        tail.next = new Node<>(tail,val);
        tail = tail.next;
        if(size %2 ==0){
            middle = middle.next;
        }
    }

    public E get(int index){
        if(index <0 || index >size){
            throw new RuntimeException("请正确传递参数!!!");
        }
        //6
        int pIndex = size / 2;
        if(index > pIndex){
            if((index - pIndex)>(size-index)){
                int t = size;
                Node<E> temp = tail;
                while (t-- > index){
                    temp =temp.prev;
                }
                return temp.data;
            }else{
                int t = pIndex;
                Node<E> temp = middle;
                while (t++ < index){
                    temp =temp.next;
                }
                return temp.data;
            }
        }else if(index < pIndex){
            return middle.data;
        }else{
            return middle.data;
        }
    }

    public static void main(String[] args) {
        DoubleLink<Integer> doubleLink = new DoubleLink<>();
        doubleLink.add(2);
        doubleLink.add(3);
        doubleLink.add(4);
        doubleLink.add(5);
        doubleLink.add(6);
        doubleLink.add(7);
        doubleLink.add(8);
        System.out.println(doubleLink.get(4));
    }

    //基础 - 容器 （就是的把基础按照某一种功能或者结构进行封装） - 【业务再进行封装】（框架）

}
